import { reactive, readonly, computed } from 'vue'
import {
  GameState,
  GameConfig,
  PlayerType,
  GamePhase,
  SEAT_POSITIONS
} from '../types/game'
import { Card, CardCombination, CardRank, CardPattern } from '../types/card'
import { generateDoubleDeck } from '../utils/cardUtils'
import { identifyCardPattern, validatePlay } from '../utils/gameLogic'
import { validateGameConfig, validatePlayerPlay } from '../utils/validation'

// AI接口调用标志（防止重复调用）
let isAIFetching = false

// 游戏状态
const gameState = reactive<GameState>({
  players: [],
  currentRound: 0,
  currentPlayer: 0,
  gamePhase: GamePhase.SETUP,
  config: {
    aiCards: [],
    trumpCard: null,
    firstPlayer: 0,
    currentLevel: 0 as CardRank // 默认打2
  },
  history: [],
  lastPlay: null,
  lastPlayerId: null,
  consecutivePasses: 0,
  aiPlaySelection: {
    selectedCards: [],
    isSelecting: false,
    isConfirming: false,
    shouldPass: false,
    hasError: false,
    errorMessage: ''
  },
  winnerTeamId: null,
  ranks: [] // 已出完玩家的ID数组
})

/**
 * 游戏状态管理组合式函数
 */
export function useGameState() {

  /**
   * 初始化玩家
   * 队伍关系：玩家1(id=1)和玩家3(id=3)是队友（队伍0）
   *          AI(id=0)和玩家2(id=2)是队友（队伍1）
   */
  const initializePlayers = () => {
    const currentLevel = gameState.config.currentLevel || 0 as CardRank

    gameState.players = [
      {
        id: 0,
        name: 'AI玩家',
        type: PlayerType.AI,
        position: SEAT_POSITIONS[0],
        handCards: [],
        currentPlay: [],
        isActive: false,
        teamId: 1, // AI和玩家2是队友
        currentLevel,
        isFinished: false
      },
      {
        id: 1,
        name: '玩家1',
        type: PlayerType.HUMAN,
        position: SEAT_POSITIONS[1],
        handCards: [],
        currentPlay: [],
        isActive: false,
        teamId: 0, // 玩家1和玩家3是队友
        currentLevel,
        isFinished: false
      },
      {
        id: 2,
        name: '玩家2',
        type: PlayerType.HUMAN,
        position: SEAT_POSITIONS[2],
        handCards: [],
        currentPlay: [],
        isActive: false,
        teamId: 1, // 玩家2和AI是队友
        currentLevel,
        isFinished: false
      },
      {
        id: 3,
        name: '玩家3',
        type: PlayerType.HUMAN,
        position: SEAT_POSITIONS[3],
        handCards: [],
        currentPlay: [],
        isActive: false,
        teamId: 0, // 玩家3和玩家1是队友
        currentLevel,
        isFinished: false
      }
    ]
  }

  /**
   * 开始游戏
   */
  const startGame = (config: GameConfig) => {
    try {
      // 验证配置
      validateGameConfig(config)

      // 保存配置
      gameState.config = { ...config }

      // 初始化玩家
      initializePlayers()

      // 设置AI玩家手牌
      const aiPlayer = gameState.players.find(p => p.id === 0)
      if (aiPlayer) {
        aiPlayer.handCards = config.aiCards
      }

      // 为人类玩家分配一些测试手牌（两副牌108张）
      const fullDeck = generateDoubleDeck()

      // 从剩余牌中为人类玩家分配手牌
      const remainingCards = fullDeck.filter(card =>
        !config.aiCards.some(aiCard => aiCard.id === card.id)
      )

      // 为每个人类玩家平均分配剩余的牌
      const humanPlayers = gameState.players.filter(p => p.type === PlayerType.HUMAN)
      const cardsPerPlayer = Math.floor(remainingCards.length / humanPlayers.length)
      humanPlayers.forEach((player, index) => {
        const startIndex = index * cardsPerPlayer
        const endIndex = Math.min(startIndex + cardsPerPlayer, remainingCards.length)
        player.handCards = remainingCards.slice(startIndex, endIndex)
      })

      // 设置当前玩家
      gameState.currentPlayer = config.firstPlayer
      gameState.players[config.firstPlayer].isActive = true

      // 重置游戏状态
      gameState.currentRound = 1
      gameState.gamePhase = GamePhase.PLAYING
      gameState.history = []
      gameState.lastPlay = null
      gameState.ranks = [] // 重置ranks数组
      gameState.consecutivePasses = 0
      gameState.winnerTeamId = null

      console.log('游戏开始', {
        firstPlayer: config.firstPlayer,
        aiCardsCount: config.aiCards.length,
        humanPlayersCards: humanPlayers.map(p => p.handCards.length),
        trumpCard: config.trumpCard,
        gamePhase: gameState.gamePhase,
        aiPlayerHandCards: aiPlayer?.handCards.length || 0
      })

      // 如果首次出牌玩家是AI，自动调用接口
      const firstPlayer = gameState.players[config.firstPlayer]
      if (firstPlayer && firstPlayer.type === PlayerType.AI) {
        console.log('首次出牌玩家是AI，自动调用接口')
        gameState.gamePhase = GamePhase.WAITING_AI
        // 延迟调用，确保游戏状态已完全初始化
        setTimeout(() => {
          fetchAISuggestion()
        }, 100)
      }

    } catch (error) {
      console.error('游戏开始失败:', error)
      throw error
    }
  }

  /**
   * 检查玩家是否可以过牌
   */
  const canPass = (playerId: number): boolean => {
    // 只有游戏刚开始（没有任何出牌历史）时，首次出牌玩家不能过牌
    // 其他任何情况（包括获得牌权后）都可以过牌
    if (gameState.history.length === 0) {
      return false
    }

    return true
  }

  /**
   * 玩家出牌
   */
  const playCards = (playerId: number, cards: Card[]) => {
    try {
      // 调试：打印传入的cards参数
      console.log('playCards - 接收到的参数:')
      console.log('  playerId:', playerId)
      console.log('  cards数量:', cards.length)
      cards.forEach((c, index) => {
        console.log(`  卡牌${index + 1}:`, {
          id: c.id,
          suit: c.suit,
          rank: c.rank,
          display: c.display,
          '完整对象': c
        })
      })

      const player = gameState.players.find(p => p.id === playerId)
      if (!player) {
        throw new Error(`玩家${playerId}不存在`)
      }

      // 验证是否轮到该玩家
      if (gameState.currentPlayer !== playerId) {
        throw new Error(`当前不是玩家${playerId}的回合`)
      }

      // 验证过牌是否合法
      if (cards.length === 0) {
        if (!canPass(playerId)) {
          throw new Error('当前情况下不能过牌，必须出牌')
        }
      }

      // 识别牌型（传递级牌信息）
      const combination = identifyCardPattern(cards, gameState.config.trumpCard)

      // 验证牌型是否有效（对所有玩家）
      if (cards.length > 0 && combination.type === CardPattern.PASS) {
        throw new Error('无效的牌型组合')
      }

      // 只对AI玩家进行严格验证
      if (player.type === PlayerType.AI) {
        // 验证出牌
        validatePlayerPlay(playerId, cards, player.handCards, true, gameState.config.trumpCard)

        // 验证牌型合法性
        if (cards.length > 0 && !validatePlay(cards, gameState.lastPlay, gameState.config.trumpCard)) {
          throw new Error('AI出牌不符合规则')
        }
      } else {
        // 人类玩家也需要验证牌型合法性
        if (cards.length > 0 && !validatePlay(cards, gameState.lastPlay, gameState.config.trumpCard)) {
          throw new Error('出牌不符合规则，无法压过上家的牌')
        }
      }

      // 更新玩家状态
      player.currentPlay = [...cards]

      // 对于人类玩家，允许任意出牌，不从手牌中移除
      // 对于AI玩家，需要从手牌中移除出牌
      if (player.type === PlayerType.AI && cards.length > 0) {
        player.handCards = player.handCards.filter(handCard =>
          !cards.some(playCard => playCard.id === handCard.id)
        )
      }

      // 记录历史
      addToHistory(playerId, cards, combination)

      // 处理出牌和过牌逻辑
      if (cards.length > 0) {
        // 出牌
        gameState.lastPlay = combination
        gameState.lastPlayerId = playerId
        gameState.consecutivePasses = 0
      } else {
        // 过牌
        gameState.consecutivePasses++

        // 如果连续3个玩家过牌，下一个玩家（最后出牌的玩家）获得牌权
        if (gameState.consecutivePasses >= 3) {
          console.log('连续3人过牌，下一个玩家获得牌权，必须出牌')
          gameState.lastPlay = null
          gameState.consecutivePasses = 0
          // lastPlayerId保持不变，下一个玩家就是获得牌权的玩家
        }
      }

      console.log(`玩家${playerId}出牌:`, {
        cards: cards.map(c => c.display),
        combination: combination.type,
        remainingCards: player.handCards.length,
        playerType: player.type,
        consecutivePasses: gameState.consecutivePasses
      })

      // 检查玩家是否出完牌
      // 方法1: AI玩家通过手牌数量判断
      // 方法2: 所有玩家通过已出牌数量判断（≥27张）
      const playerPlayedCount = gameState.history
        .filter(h => h.playerId === playerId)
        .reduce((sum, h) => sum + h.cards.length, 0)

      const isFinished = player.type === PlayerType.AI
        ? player.handCards.length === 0
        : playerPlayedCount >= 27

      if (isFinished && !player.isFinished) {
        player.isFinished = true

        // 添加到ranks数组
        if (!gameState.ranks.includes(playerId)) {
          gameState.ranks.push(playerId)
          console.log(`玩家${playerId}出完牌,添加到ranks数组`, {
            playedCount: playerPlayedCount,
            ranks: gameState.ranks
          })
        }

        console.log(`玩家${playerId}出完牌`, {
          playerType: player.type,
          playedCount: playerPlayedCount,
          handCardsCount: player.handCards.length
        })

        // 检查游戏是否结束
        if (checkGameEnd()) {
          return
        }
      }

      // 如果是AI玩家出牌，清空AI建议区域
      if (player.type === PlayerType.AI) {
        gameState.aiPlaySelection.selectedCards = []
        gameState.aiPlaySelection.isSelecting = false
        gameState.aiPlaySelection.shouldPass = false
        gameState.aiPlaySelection.hasError = false
        gameState.aiPlaySelection.errorMessage = ''
      }

      // 切换到下一个玩家
      nextPlayer()

    } catch (error) {
      console.error('出牌失败:', error)
      throw error
    }
  }

  /**
   * 切换到下一个玩家 (按玩家ID逆时针递增)
   * 界面布局:     玩家2(上)
   *         玩家3(左)   玩家1(右)
   *              AI(下)
   * 逆时针出牌顺序(按ID): AI(0,下) → 玩家1(1,右) → 玩家2(2,上) → 玩家3(3,左) → AI(0,下)...
   */
  const nextPlayer = () => {
    // 取消当前玩家的激活状态
    gameState.players[gameState.currentPlayer].isActive = false

    // 按玩家ID递增方向切换到下一个玩家 (0→1→2→3→0...)
    // 这样在界面上呈现逆时针: 下→右→上→左→下
    const counterclockwiseOrder = [0, 1, 2, 3] // AI→玩家1→玩家2→玩家3
    let currentIndex = counterclockwiseOrder.indexOf(gameState.currentPlayer)
    let attempts = 0

    // 找到下一个未出完牌的玩家
    do {
      currentIndex = (currentIndex + 1) % 4
      gameState.currentPlayer = counterclockwiseOrder[currentIndex]
      attempts++

      // 防止无限循环
      if (attempts > 4) {
        console.error('无法找到下一个玩家')
        break
      }
    } while (gameState.players[gameState.currentPlayer].isFinished)

    gameState.players[gameState.currentPlayer].isActive = true

    console.log(`轮到玩家${gameState.currentPlayer}出牌 (${gameState.players[gameState.currentPlayer].name})`)

    // 检查游戏是否已结束,如果已结束则不再调用AI接口
    if (gameState.gamePhase === GamePhase.FINISHED) {
      console.log('游戏已结束,不再调用AI接口')
      return
    }

    // 如果轮到AI玩家，自动调用AI接口
    if (gameState.players[gameState.currentPlayer].type === PlayerType.AI) {
      gameState.gamePhase = GamePhase.WAITING_AI
      // 自动调用AI接口
      fetchAISuggestion()
    } else {
      gameState.gamePhase = GamePhase.PLAYING
    }
  }

  /**
   * 调用接口获取AI建议出牌
   */
  const fetchAISuggestion = async () => {
    // 防止重复调用
    if (isAIFetching) {
      return
    }

    try {
      isAIFetching = true

      const aiPlayer = getAIPlayer.value
      if (!aiPlayer) {
        console.error('AI玩家不存在')
        return
      }


      console.log('AI玩家手牌详情:', aiPlayer.handCards.map(c => ({
        id: c.id,
        suit: c.suit,
        rank: c.rank,
        display: c.display
      })))

      // 检查是否有无效的卡牌ID
      const invalidCards = aiPlayer.handCards.filter(c => {
        const id = c.id
        return !(
          (id >= 256 && id <= 268) ||   // 方块
          (id >= 512 && id <= 524) ||   // 梅花
          (id >= 768 && id <= 780) ||   // 红桃
          (id >= 1024 && id <= 1036) || // 黑桃
          id === 1037 || id === 1294 || // 大小王
          (id >= 10256 && id <= 10268) ||   // 方块(第二副)
          (id >= 10512 && id <= 10524) ||   // 梅花(第二副)
          (id >= 10768 && id <= 10780) ||   // 红桃(第二副)
          (id >= 11024 && id <= 11036) ||   // 黑桃(第二副)
          id === 11037 || id === 11294      // 大小王(第二副)
        )
      })

      if (invalidCards.length > 0) {
        console.error('AI手牌中包含无效的卡牌ID:', invalidCards)
        console.error('请检查AI手牌的选择过程，确保使用正确的卡牌ID')
        return
      }

      // 动态导入服务
      const { playCard, buildPlayRequest } = await import('../services/aiService')
      const { convertAPIIdsToCards } = await import('../utils/cardUtils')

      // 构建请求
      const request = buildPlayRequest(gameState, aiPlayer.id, `game-${Date.now()}`)

      console.log('出牌请求:', request)

      // 调用接口
      const response = await playCard(request)

      console.log('出牌响应:', response)

      if (response.code === 0 && response.pattern === 0) {
        // AI建议过牌 (pattern = 0)
        console.log('AI建议过牌')
        gameState.aiPlaySelection.selectedCards = []
        gameState.aiPlaySelection.isSelecting = true
        gameState.aiPlaySelection.shouldPass = true
        gameState.aiPlaySelection.hasError = false
        gameState.aiPlaySelection.errorMessage = ''
      } else if (response.code === 0 && response.action && response.action.length > 0) {
        // 转换API格式ID为卡牌对象（这些是API返回的建议ID）
        const suggestedAPICards = convertAPIIdsToCards(response.action)

        console.log('AI建议出牌（API格式）:', suggestedAPICards.map(c => c.display))

        // 从AI手牌中查找对应的卡牌（使用实际的卡牌对象）
        const actualCards: Card[] = []
        for (const apiCard of suggestedAPICards) {
          // 在AI手牌中查找匹配的牌（相同花色和点数）
          const matchingCard = aiPlayer.handCards.find(handCard =>
            handCard.suit === apiCard.suit && handCard.rank === apiCard.rank &&
            !actualCards.some(c => c.id === handCard.id) // 避免重复选择同一张牌
          )

          if (matchingCard) {
            actualCards.push(matchingCard)
          } else {
            console.warn(`AI手牌中未找到匹配的牌: ${apiCard.display}`)
          }
        }

        console.log('从AI手牌中找到的实际卡牌:', actualCards.map(c => `${c.display}(ID:${c.id})`))

        // 自动选择建议的牌（使用AI手牌中的实际卡牌对象）
        gameState.aiPlaySelection.selectedCards = actualCards
        gameState.aiPlaySelection.isSelecting = true
        gameState.aiPlaySelection.shouldPass = false
        gameState.aiPlaySelection.hasError = false
        gameState.aiPlaySelection.errorMessage = ''

        // 显示提示信息
        console.log(`AI建议出牌: ${actualCards.map(c => c.display).join(', ')} (牌型: ${response.pattern})`)
      } else {
        console.warn('接口返回异常，使用降级策略')
        // 接口返回异常
        gameState.aiPlaySelection.selectedCards = []
        gameState.aiPlaySelection.isSelecting = true
        gameState.aiPlaySelection.shouldPass = false
        gameState.aiPlaySelection.hasError = true
        gameState.aiPlaySelection.errorMessage = '接口返回异常'
      }
    } catch (error) {
      console.error('获取AI建议失败:', error)
      // 接口调用失败
      gameState.aiPlaySelection.selectedCards = []
      gameState.aiPlaySelection.isSelecting = true
      gameState.aiPlaySelection.shouldPass = false
      gameState.aiPlaySelection.hasError = true
      gameState.aiPlaySelection.errorMessage = error instanceof Error ? error.message : '接口调用失败'
    } finally {
      // 重置标志，允许下次调用
      isAIFetching = false
    }
  }

  /**
   * AI出牌
   */
  const aiPlay = (cards: Card[]) => {
    try {
      const aiPlayer = gameState.players.find(p => p.type === PlayerType.AI)
      if (!aiPlayer) {
        throw new Error('AI玩家不存在')
      }

      // 验证AI是否轮到出牌
      if (gameState.currentPlayer !== aiPlayer.id) {
        throw new Error('当前不是AI的回合')
      }

      // AI出牌
      playCards(aiPlayer.id, cards)

      // 切换回游戏状态
      if (gameState.gamePhase === GamePhase.WAITING_AI) {
        gameState.gamePhase = GamePhase.PLAYING
      }

    } catch (error) {
      console.error('AI出牌失败:', error)
      throw error
    }
  }

  /**
   * 调用AI决策
   */
  const callAI = async () => {
    try {
      if (gameState.gamePhase !== GamePhase.PLAYING) {
        throw new Error('游戏状态不正确，无法调用AI')
      }

      const currentPlayer = gameState.players.find(p => p.id === gameState.currentPlayer)
      if (!currentPlayer || currentPlayer.type !== PlayerType.AI) {
        throw new Error('当前玩家不是AI')
      }

      // 切换到等待AI状态
      gameState.gamePhase = GamePhase.WAITING_AI

      // 这里返回当前游戏状态，供外部调用AI服务
      return gameState

    } catch (error) {
      console.error('调用AI失败:', error)
      throw error
    }
  }

  /**
   * 添加历史记录
   */
  const addToHistory = (playerId: number, cards: Card[], combination: CardCombination) => {
    const player = gameState.players.find(p => p.id === playerId)
    if (!player) return

    const historyRecord = {
      id: `${Date.now()}-${playerId}`,
      round: gameState.currentRound,
      playerId,
      playerName: player.name,
      cards: [...cards],
      combination,
      timestamp: new Date()
    }

    gameState.history.push(historyRecord)
  }

  /**
   * 检查游戏是否结束
   * 当一个队伍的两个玩家都出完牌时，游戏结束
   */
  const checkGameEnd = (): boolean => {
    // 检查每个队伍
    for (let teamId = 0; teamId <= 1; teamId++) {
      const teamPlayers = gameState.players.filter(p => p.teamId === teamId)
      const finishedCount = teamPlayers.filter(p => p.isFinished).length

      // 如果一个队伍的两个玩家都出完牌
      if (finishedCount === 2) {
        endGame(teamId)
        return true
      }

      // 如果一个队伍有一个玩家出完牌
      if (finishedCount === 1) {
        console.log(`队伍${teamId}有一个玩家出完牌`)
      }
    }

    return false
  }

  /**
   * 结束游戏
   */
  const endGame = (winnerTeamId: number) => {
    gameState.gamePhase = GamePhase.FINISHED
    gameState.winnerTeamId = winnerTeamId

    // 取消所有玩家的激活状态
    gameState.players.forEach(player => {
      player.isActive = false
    })

    const winnerPlayers = gameState.players.filter(p => p.teamId === winnerTeamId)
    console.log(`游戏结束，队伍${winnerTeamId}获胜!`, {
      winners: winnerPlayers.map(p => p.name)
    })

    // 升级逻辑
    handleLevelUp(winnerTeamId)
  }

  /**
   * 处理升级
   */
  const handleLevelUp = (winnerTeamId: number) => {
    const winnerPlayers = gameState.players.filter(p => p.teamId === winnerTeamId)
    const bothFinished = winnerPlayers.every(p => p.isFinished)

    // 双下升3级，单下升1级
    const levelUp = bothFinished ? 3 : 1

    winnerPlayers.forEach(player => {
      const newLevel = Math.min(player.currentLevel + levelUp, 12) // 最高打到A
      player.currentLevel = newLevel as CardRank
      console.log(`${player.name}升级到${newLevel}`)
    })
  }

  /**
   * 标记玩家已出完牌
   */
  const markPlayerFinished = (playerId: number) => {
    const player = gameState.players.find(p => p.id === playerId)
    if (!player) {
      throw new Error(`玩家${playerId}不存在`)
    }

    // 不允许标记AI玩家
    if (player.type === PlayerType.AI) {
      throw new Error('不能手动标记AI玩家为已出完')
    }

    // 如果玩家已经标记为出完,不重复添加
    if (player.isFinished) {
      console.log(`玩家${playerId}(${player.name})已经标记为出完牌`)
      return
    }

    // 更新玩家状态
    player.isFinished = true

    // 添加到ranks数组
    if (!gameState.ranks.includes(playerId)) {
      gameState.ranks.push(playerId)
    }

    console.log(`玩家${playerId}(${player.name})已标记为出完牌`, {
      ranks: gameState.ranks
    })

    // 检查是否所有人类玩家都已出完
    const humanPlayers = gameState.players.filter(p => p.type === PlayerType.HUMAN)
    const allHumanFinished = humanPlayers.every(p => p.isFinished)

    if (allHumanFinished) {
      // 所有人类玩家都出完了,AI玩家自动成为最后一名
      const aiPlayer = gameState.players.find(p => p.type === PlayerType.AI)
      if (aiPlayer && !aiPlayer.isFinished) {
        aiPlayer.isFinished = true
        if (!gameState.ranks.includes(aiPlayer.id)) {
          gameState.ranks.push(aiPlayer.id)
        }
        console.log('所有人类玩家已出完,AI玩家自动成为最后一名', {
          ranks: gameState.ranks
        })

        // 触发游戏结束
        gameState.gamePhase = GamePhase.FINISHED

        // 游戏已结束,不再调用nextPlayer
        return
      }
    }

    // 如果当前轮到该玩家,自动跳到下一个玩家(仅在游戏未结束时)
    if (gameState.currentPlayer === playerId && gameState.gamePhase !== GamePhase.FINISHED) {
      nextPlayer()
    }
  }

  /**
   * 重置游戏
   */
  const resetGame = () => {
    gameState.players = []
    gameState.currentRound = 0
    gameState.currentPlayer = 0
    gameState.gamePhase = GamePhase.SETUP
    gameState.config = {
      aiCards: [],
      trumpCard: null,
      firstPlayer: 0,
      currentLevel: 0 as CardRank
    }
    gameState.history = []
    gameState.lastPlay = null
    gameState.lastPlayerId = null
    gameState.consecutivePasses = 0
    gameState.aiPlaySelection = {
      selectedCards: [],
      isSelecting: false,
      isConfirming: false,
      shouldPass: false,
      hasError: false,
      errorMessage: ''
    }
    gameState.winnerTeamId = null
    gameState.ranks = [] // 重置ranks数组
  }

  /**
   * 获取当前玩家
   */
  const getCurrentPlayer = computed(() => {
    return gameState.players.find(p => p.id === gameState.currentPlayer)
  })

  /**
   * 获取AI玩家
   */
  const getAIPlayer = computed(() => {
    return gameState.players.find(p => p.type === PlayerType.AI)
  })

  /**
   * 检查是否可以开始游戏
   */
  const canStartGame = computed(() => {
    return gameState.gamePhase === GamePhase.SETUP
  })

  /**
   * 检查是否在游戏中
   */
  const isGameActive = computed(() => {
    return gameState.gamePhase === GamePhase.PLAYING || gameState.gamePhase === GamePhase.WAITING_AI
  })

  /**
   * 检查是否等待AI
   */
  const isWaitingAI = computed(() => {
    return gameState.gamePhase === GamePhase.WAITING_AI
  })

  /**
   * 选择AI卡牌
   */
  const selectAICard = (card: Card) => {
    try {
      // 调试：检查传入的卡牌对象
      console.log('selectAICard - 传入的卡牌:', {
        id: card.id,
        suit: card.suit,
        rank: card.rank,
        display: card.display
      })

      const aiPlayer = getAIPlayer.value
      if (!aiPlayer) {
        throw new Error('AI玩家不存在')
      }

      // 验证是否轮到AI出牌
      if (gameState.currentPlayer !== aiPlayer.id) {
        throw new Error('当前不是AI的回合')
      }

      // 验证卡牌是否在AI手牌中
      const cardExists = aiPlayer.handCards.some(handCard => handCard.id === card.id)
      if (!cardExists) {
        console.error('卡牌不在AI手牌中:', {
          cardId: card.id,
          aiHandCardIds: aiPlayer.handCards.map(c => c.id)
        })
        throw new Error('选择的卡牌不在AI手牌中')
      }

      // 检查是否已经选中
      const isSelected = gameState.aiPlaySelection.selectedCards.some(selectedCard => selectedCard.id === card.id)

      if (isSelected) {
        // 取消选择
        gameState.aiPlaySelection.selectedCards = gameState.aiPlaySelection.selectedCards.filter(
          selectedCard => selectedCard.id !== card.id
        )
      } else {
        // 添加选择
        gameState.aiPlaySelection.selectedCards.push(card)
      }

      // 设置选择状态
      gameState.aiPlaySelection.isSelecting = true

      console.log('AI卡牌选择更新:', {
        selectedCount: gameState.aiPlaySelection.selectedCards.length,
        selectedCards: gameState.aiPlaySelection.selectedCards.map(c => c.display)
      })

    } catch (error) {
      console.error('选择AI卡牌失败:', error)
      throw error
    }
  }

  /**
   * 取消选择AI卡牌
   */
  const deselectAICard = (card: Card) => {
    gameState.aiPlaySelection.selectedCards = gameState.aiPlaySelection.selectedCards.filter(
      selectedCard => selectedCard.id !== card.id
    )
  }

  /**
   * 清空AI选择
   */
  const clearAISelection = () => {
    gameState.aiPlaySelection.selectedCards = []
    gameState.aiPlaySelection.isSelecting = false
    gameState.aiPlaySelection.isConfirming = false
  }

  /**
   * 验证AI选择
   */
  const validateAISelection = (): boolean => {
    try {
      const selectedCards = gameState.aiPlaySelection.selectedCards

      // 空选择是合法的（过牌）
      if (selectedCards.length === 0) {
        return true
      }

      // 如果有选中的牌，直接返回true（AI建议的牌已经过接口验证）
      // 不需要再次验证牌型合法性，因为这些牌是AI接口返回的建议
      if (selectedCards.length > 0) {
        return true
      }

      return true
    } catch (error) {
      console.error('验证AI选择失败:', error)
      return false
    }
  }

  /**
   * 确认AI出牌
   */
  const confirmAIPlay = () => {
    try {
      const aiPlayer = getAIPlayer.value
      if (!aiPlayer) {
        throw new Error('AI玩家不存在')
      }

      // 验证是否轮到AI出牌
      if (gameState.currentPlayer !== aiPlayer.id) {
        throw new Error('当前不是AI的回合')
      }

      // 验证选择是否有效
      if (!validateAISelection()) {
        throw new Error('AI选择的牌型不符合规则')
      }

      // 设置确认状态
      gameState.aiPlaySelection.isConfirming = true

      // 执行出牌
      const selectedCards = [...gameState.aiPlaySelection.selectedCards]

      // 调试：检查选中的卡牌
      console.log('confirmAIPlay - 选中的卡牌详细信息:')
      selectedCards.forEach((c, index) => {
        console.log(`  卡牌${index + 1}:`, {
          id: c.id,
          suit: c.suit,
          rank: c.rank,
          display: c.display,
          '完整对象': c
        })
      })

      playCards(aiPlayer.id, selectedCards)

      // 清空选择状态
      clearAISelection()

      console.log('AI出牌确认完成:', {
        playedCards: selectedCards.map(c => c.display)
      })

    } catch (error) {
      console.error('确认AI出牌失败:', error)
      // 重置确认状态
      gameState.aiPlaySelection.isConfirming = false
      throw error
    }
  }

  /**
   * 检查AI是否可以确认出牌
   */
  const canConfirmAIPlay = computed(() => {
    const isSelecting = gameState.aiPlaySelection.isSelecting
    const isValid = validateAISelection()
    const isNotConfirming = !gameState.aiPlaySelection.isConfirming

    console.log('canConfirmAIPlay检查:', {
      isSelecting,
      isValid,
      isNotConfirming,
      selectedCardsCount: gameState.aiPlaySelection.selectedCards.length,
      result: isSelecting && isValid && isNotConfirming
    })

    return isSelecting && isValid && isNotConfirming
  })

  /**
   * 获取队伍信息
   */
  const getTeamInfo = computed(() => {
    return {
      team0: gameState.players.filter(p => p.teamId === 0),
      team1: gameState.players.filter(p => p.teamId === 1)
    }
  })

  /**
   * 获取当前玩家的队友
   */
  const getTeammate = (playerId: number) => {
    const player = gameState.players.find(p => p.id === playerId)
    if (!player) return null

    return gameState.players.find(p => p.id !== playerId && p.teamId === player.teamId)
  }

  /**
   * 重置游戏时也要重置AI选择状态
   */
  const resetGameWithAI = () => {
    resetGame()
    clearAISelection()
  }

  return {
    // 状态
    gameState: readonly(gameState),

    // 计算属性
    getCurrentPlayer,
    getAIPlayer,
    canStartGame,
    isGameActive,
    isWaitingAI,
    canConfirmAIPlay,
    getTeamInfo,

    // 方法
    startGame,
    playCards,
    aiPlay,
    callAI,
    nextPlayer,
    resetGame: resetGameWithAI,
    addToHistory,
    getTeammate,
    checkGameEnd,
    canPass,
    markPlayerFinished,

    // AI选择相关方法
    selectAICard,
    deselectAICard,
    clearAISelection,
    validateAISelection,
    confirmAIPlay
  }
}

